﻿<?php
/**
* wechat php test
*/

date_default_timezone_set('Asia/Hong_Kong');  //set time zone

define("TOKEN", "doucube");
$max_size = 500000;

$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
$wechatObj->responseMsg();

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        logger(" R ".$postStr);
        //extract post data
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            
            switch ($RX_TYPE)
            {
                case "text":
                    $resultStr = $this->receiveText($postObj);
                    break;
                case "image":
                    $resultStr = $this->receiveImage($postObj);
                    break;
                case "location":
                    $resultStr = $this->receiveLocation($postObj);
                    break;
                default:
                    $resultStr = "unknow msg type";
                    break;
            }
            logger(" T ".$resultStr);
            echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    private function receiveText($object)
    {
        $funcFlag = 0;
        $keyword = trim($object->Content);
        
        $contentStr = simsimiAPI($keyword);
        
        $resultStr = $this->transmitText($object, $contentStr, $funcFlag);

        // if($keyword == "?"){
            // $contentStr = "2253欢迎使用有道英语查询，输入要查询的单词，可获得翻译结果！";
            // $funcFlag = 0;
			// $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        // }
		// else if($keyword == "0"){
			// $contentStr = "Welcome"."\r\n"."to"."\r\n"."wechat"."\r\n"."world";
			// $resultStr = $this->transmitText($object, $contentStr);
        // }
		// else if($keyword == "1"){
            // $resultStr = $this->transmitNews($object);
        // }
        // else if($keyword == "2"){
            // $contentStr = customReply($keyword);
			// $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        // }
        // else {
            // $contentStr = translate($keyword);
			// $resultStr = $this->transmitText($object, $contentStr);
        // }

        
        //Content 消息内容，大小限制在2048字节，字段为空为不合法请求
        //$resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        return $resultStr;
    }
	
    private function receiveImage($object)
    {
        $contentStr = "receive a picture, url: ".$object->PicUrl;
        $resultStr = $this->transmitText($object, $contentStr);
        return $resultStr;
    }
    
    private function receiveLocation($object)
    {
        $contentStr = "receive a location, 经度:".$object->Location_X." 纬度:".$object->Location_Y." 位置:".$object->Label;
        $resultStr = $this->transmitText($object, $contentStr);
        return $resultStr;
    }
    
    private function transmitText($object, $content, $flag = 0)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%d</FuncFlag>
</xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);

        return $resultStr;
    }
	
    private function transmitNews($object)
    {
    //首条标题28字
    //其他标题39字
	$itemTpl = "
<item>
	<Title><![CDATA[%s]]></Title>
	<Discription><![CDATA[%s]]></Discription>
	<PicUrl><![CDATA[%s]]></PicUrl> 
	<Url><![CDATA[%s]]></Url>
</item>";
        $newsTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[news]]></MsgType>
    <Content><![CDATA[]]></Content>
    <ArticleCount>%s</ArticleCount>
    <Articles>
$item_str
    </Articles>
    <FuncFlag>%s</FuncFlag>
</xml> 
eot";
	// <Title><![CDATA[多条图文消息半了晴十多条图文消息半了晴十多条图文消息二八]]></Title>
	// <Title><![CDATA[深圳 温度:20℃ 湿度:241%%￥%$%￥ 风向:东北风 空气:轻度污染]]></Title>
    $temp = "<xml>
 <ToUserName><![CDATA[%s]]></ToUserName>
 <FromUserName><![CDATA[%s]]></FromUserName>
 <CreateTime>%s</CreateTime>
 <MsgType><![CDATA[news]]></MsgType>
 <Content><![CDATA[]]></Content>
 <ArticleCount>10</ArticleCount>
 <Articles>
 <item>
 <Title><![CDATA[【深圳】天气实况 温度:-2℃ 湿度:241％ 风速:西北风3级]]></Title>
 <Description><![CDATA[Description 1]]></Description>
 <PicUrl><![CDATA[http://weixin.doucube.com/doucube/image0.jpg]]></PicUrl>
 <Url><![CDATA[]]></Url>
 </item>
 <item>
 <Title><![CDATA[今天:12℃~25℃ 多云 微风]]></Title>
 <Description><![CDATA[Description2]]></Description>
 <PicUrl><![CDATA[http://weixin.doucube.com/doucube/image2.jpg]]></PicUrl>
 <Url><![CDATA[http://txw1958.cnblogs.com/]]></Url>
 </item>
 <item>
 <Title><![CDATA[明天:14℃~24℃ 多云 微风转北风3-4级]]></Title>
 <Description><![CDATA[description3]]></Description>
 <PicUrl><![CDATA[http://weixin.doucube.com/doucube/image3.jpg]]></PicUrl>
 <Url><![CDATA[]]></Url>
 </item>
 <item>
 <Title><![CDATA[01月22日：3℃~6℃ 阴转小雨 北风小于3级]]></Title>
 <Description><![CDATA[description4]]></Description>
 <PicUrl><![CDATA[http://weixin.doucube.com/doucube/image3.jpg]]></PicUrl>
 <Url><![CDATA[]]></Url>
 </item>
 <item>
 <Title><![CDATA[01月23日：3℃~6℃ 阴转小雨 北风小于3级]]></Title>
 <Description><![CDATA[]]></Description>
 <PicUrl><![CDATA[]]></PicUrl>
 <Url><![CDATA[]]></Url>
 </item>
 <item>
 <Title><![CDATA[6]]></Title>
 <Description><![CDATA[]]></Description>
 <PicUrl><![CDATA[]]></PicUrl>
 <Url><![CDATA[]]></Url>
 </item>
 <item>
 <Title><![CDATA[title7后天天气]]></Title>
 <Description><![CDATA[description3]]></Description>
 <PicUrl><![CDATA[http://weixin.doucube.com/doucube/image3.jpg]]></PicUrl>
 <Url><![CDATA[]]></Url>
 </item>
 <item>
 <Title><![CDATA[title8后天天气]]></Title>
 <Description><![CDATA[description3]]></Description>
 <PicUrl><![CDATA[http://weixin.doucube.com/doucube/image3.jpg]]></PicUrl>
 <Url><![CDATA[]]></Url>
 </item>
 <item>
 <Title><![CDATA[title9后天天气]]></Title>
 <Description><![CDATA[description3]]></Description>
 <PicUrl><![CDATA[http://weixin.doucube.com/doucube/image3.jpg]]></PicUrl>
 <Url><![CDATA[]]></Url>
 </item>
 <item>
 <Title><![CDATA[title10后天天气]]></Title>
 <Description><![CDATA[description3]]></Description>
 <PicUrl><![CDATA[http://weixin.doucube.com/doucube/image3.jpg]]></PicUrl>
 <Url><![CDATA[]]></Url>
 </item>
 </Articles>
 <FuncFlag>0</FuncFlag>
 </xml>";
        $resultStr = sprintf($temp, $object->FromUserName, $object->ToUserName, time());

        return $resultStr;
    }
}

function logger($log_content)
{
    Global $max_size;
    $log_filename = date("Ymd").".xml";
    if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);sleep(1);}
    file_put_contents($log_filename, date('H:i:s').$log_content."\r\n", FILE_APPEND);
}

function customReply($keyword)
{
    if ((double)$keyword > 0 and (double)$keyword < 100){
        return "Message: ".$keyword;
    }else{
        return "Unknown: ".$keyword;
    }
}

function simsimiAPI($keyword)
{
    $url = "http://api.simsimi.com/request.p?key=your key&lc=en&ft=1.0&text=".urlencode($keyword);

    //params = array();
    $params['key'] = "f4aa59f8-b8cc-425d-9d86-3938a67420f7";
    $params['lc'] = "ch";
    $params['ft'] = "1.0";
    $params['text'] = $keyword;

    $url = "http://api.simsimi.com/request.p?".http_build_query($params);

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($ch);
	curl_close($ch);

    if ($output === FALSE){
        return "cURL Error: ". curl_error($ch);
    }
    $message = json_decode($output,true);
    if($message['result'] == '100'){
        return $message['response'];
    }else{
        return "ERROR! ".$message['result']."-".$message['msg'];
    }
}
?>